<?php
/**
* A simple database connector
* @link http://webappkit.net
* @package dblink
* @subpackage mysql
* @author J.Ducastel <jeremie@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

/**
*
* @author J.Ducastel <jeremie@ducastel.name>
* @version
*/
class DbLinkTool_Mysql extends WakTool {

    protected $cfg=array(
        'host'=>'localhost'
        ,'db'=>''
        ,'user'=>'root'
        ,'login'=>''
        ,'encoding'=>'');

    static function Factory($kit_id,$cfg) {
        return new DblinkTool_Mysql($kit_id,$cfg);
    }

    public function connect() {
        // trying to connect user to host
        $host=$this->cfg['host'];
        $user=$this->cfg['user'];
        $pwd=$this->cfg['pwd'];
        if (!$this->link=@mysql_connect($host,$user,$pwd)) {
			//trigger_error("dbLink_mysql->connectUser couldn't connect to host ".$this->host." ".strlen($login)."/".strlen($pwd),E_USER_WARNING);
            throw new Exception("could not connect user $user to host $host");
			return false;
		}
        // selecting db
        $db=$this->cfg['db'];
        if (!$this->selectDb($db)) {
            throw new Exception("could not select db $db");
            // print_r($this);
            return false;
        }
        // setting encoding
        if ($encoding=$this->cfg['encoding'] and !$this->setEncoding($encoding)) {
            throw new Exception("could not set encoding $encoding");
            // print_r($this);
            return false;
        }
    }

    public function selectDb($db) {
		return @mysql_select_db($db, $this->link);
    }

	/**
	* executes a sql query, return resource
	* @access public
	* @param string $sql sql query
	* @param bool $buffered default to false
	* @return resource
	*/
	function & query($sql,$buffered=false) {
		// execute query
		if ($buffered) {
			$r=@mysql_query($sql,$this->link);
		} else {
			$r=@mysql_unbuffered_query($sql,$this->link);
		}
		return $r;
	}

    public function setEncoding($encoding) {
		// MySQL 4.0
		if (!$this->query("SET CHARACTER SET '$encoding'")) {
			//trigger_error('dbLink_mysql->setEncoding: failed to set encoding '.$encoding,E_USER_WARNING);
			return false;
		}
		// MySQL 4.1
		if (!$this->query("SET NAMES '$encoding'")) {
			// trigger_error('dbLink_mysql->setEncoding: failed to set encoding '.$encoding,E_USER_WARNING);
			return false;
		}
		$this->encoding=$encoding;
		// echo "<p>encoding $encoding set for db transactions</p>";
		return true;
    }
}
?>